package com.tueye.web.controller;

import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.RequestMapping;

import com.tueye.ajax.json.JSONArray;
import com.tueye.ajax.json.JSONObject;
import com.tueye.entity.TopicComment;
import com.tueye.entity.Topics;
import com.tueye.entity.user.Flowers;
import com.tueye.entity.user.User;
import com.tueye.service.ITopicCommentService;
import com.tueye.service.ITopicService;
import com.tueye.utils.HtmlConverseUtil;
import com.tueye.utils.TuEyeConstant;
import com.tueye.utils.UUIDGenerator;
/**
 * 文章评论
 * @author hanxiaowei
 *
 */
@SuppressWarnings("unchecked")
@org.springframework.stereotype.Controller
@RequestMapping("/topicComment.do")
public class TopicCommentController {

	private Log log = LogFactory.getLog(TopicCommentController.class);
	
	@Autowired
	@Qualifier("topicCommentService")
	private ITopicCommentService topicCommentService;
	
	@Autowired
	@Qualifier("topicService")
	ITopicService topicService;
	
	@RequestMapping(params = "action=getTopicCommentHtml")
	public String getTopicCommentHtml (HttpServletRequest request, HttpServletResponse response) throws Exception {
		
		response.setContentType("text/html;charset=UTF-8");   
		response.setHeader("Cache-Control","no-cache");   
		try {
			JSONObject json = new JSONObject();
			JSONArray members = new JSONArray();
			String topicId = request.getParameter("topicId");
			String hql = "from TopicComment t Where t.topic.id ='" + topicId + "' order by sys_time asc";
			List<TopicComment> topicCommentList = this.topicCommentService
					.getTopicCommentByHql(hql);
			/*Topics topic = topicService.getTopicById(topicId);
			//查上一篇,本topic 的code大于上一篇，且上一篇按日期倒序
			 String upsql = "select   t.topic_title,t.topic_code from tueye_topics_info t where t.topic_code<" + topic.getTopic_code() +" and t.topic_type_id='"+topic.getTopic_type().getId()+"' order by t.topic_uploaddate desc limit 1";
			 StringBuffer sb = new StringBuffer("上一篇作品:");
			 List uplist = topicService.queryBysql(upsql);
			 if(uplist.size() == 0){
				 sb.append("<a href='../../index.html' title='返回首页'>返回首页</a>");
			 }else{
				 Object[] obj = (Object[]) uplist.get(0);
				 sb.append("<a href='../").append(obj[1]).append("/index.html' title='")
				 .append(obj[0]).append("'>").append(obj[0]).append("</a>");
			 }*/
			if (topicCommentList.size() > 0) {
				for (int i = 0; i < topicCommentList.size(); i++) {
					TopicComment topicComment = topicCommentList.get(i);
					JSONObject member = new JSONObject().put("commentPeople",
							topicComment.getCommentPeople()).put("content",
							replaceBianqing(topicComment.getContent())).put("topicId",
							topicComment.getTopic().getId()).put("SysTime", topicComment.getSys_time())
							//.put("upTopic", sb.toString());
							;
					members.put(i, member);
				}
			}
			json.put("topicComments", members);
			response.getWriter().write(json.toString());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	@RequestMapping(params = "action=addTopicComment")
	public String addTopicComment (HttpServletRequest request, HttpServletResponse response) throws Exception {
		
		response.setContentType("text/html;charset=UTF-8");   
		response.setHeader("Cache-Control","no-cache");  
		
		try {
			String topicId = request.getParameter("topicid");
			String commentPeople = request.getParameter("commentPeople");
			String content = request.getParameter("content");
			content = HtmlConverseUtil.getInstance().encode(content);
			TopicComment topicComment = new TopicComment();
			topicComment.setCommentPeople(commentPeople);
			topicComment.setContent(content);
			topicComment.setId(UUIDGenerator.getUUID());
			User user = (User) request.getSession().getAttribute(
					TuEyeConstant.TUEYE_USER);
			if (user == null) {
				topicComment.setSys_fille("匿名");
			} else {
				topicComment.setSys_fille(user.getByname());
			}
			topicComment.setSys_time(new Date());
			Topics topics = new Topics();
			topics.setId(topicId);
			topicComment.setTopic(topics);
			this.topicCommentService.addTopicComment(topicComment);
			response.getWriter().println("s=1");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	/**
	 * 踩一下，顶一下
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(params = "action=addDingOrCai")
	public String addDingOrCai (HttpServletRequest request, HttpServletResponse response) throws Exception {
		
		String topicId = request.getParameter("topicId");
		String type = request.getParameter("type");
		Flowers fowers = new Flowers();
		try {
			String hql = "";
			if (type.equalsIgnoreCase("1")) {
				fowers.setId(UUIDGenerator.getUUID());
				fowers.setFlowersNum(1);
				fowers.setClientToken(this.getIpAddr(request));
				fowers.setSys_time(new Date());
				//flowersNum
			} else if (type.equalsIgnoreCase("2")) {
				//CaiNum
				fowers.setId(UUIDGenerator.getUUID());
				fowers.setCaiNum(1);
				fowers.setClientToken(this.getIpAddr(request));
				fowers.setSys_time(new Date());
			}
			this.topicCommentService.addFlowers(fowers);
			response.getWriter().println("s=1");
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return null;
	}
	/**
	 * 判定该客户端是否可用该操作
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(params = "action=isExistDingOrCai")
	public String isExistDingOrCai (HttpServletRequest request, HttpServletResponse response) throws Exception {
		
		String topicsId = request.getParameter("topicId");
		String count = request.getParameter("count");
		String clientToken =  this.getIpAddr(request);
		String sql = "SELECT t.id FROM tueye_flowers_info t where clientToken='"+clientToken+"' and topics_id ='"+topicsId+"'" +
				" and year(sys_time) ="+com.tueye.utils.DateUtils.getYear()+" " +
						"and month(sys_time)="+com.tueye.utils.DateUtils.getMonth()+" " +
								"and day(sys_time) ="+com.tueye.utils.DateUtils.getDay();
		List ls = this.topicService.queryBysql(sql);
		//增加顶、踩的数量
		int doCount = Integer.parseInt(count) ;
		String reStr ="";
		if(doCount == 1 || doCount == -1 ){
			Flowers flower = null;
			List list =  topicService.getFlowerByTopicsId(topicsId);
			if(list.size()>0)
			{
				flower = (Flowers)list.get(0);
			}
			if(flower == null){
				flower = new Flowers();
				flower.setId(new UUIDGenerator().getUUID());
			}
			Topics topics = new Topics ();
			topics.setId(topicsId);
			flower.setTopics(topics);
			
			if(doCount == -1)
				flower.setCaiNum(1 + (flower.getCaiNum() == null ? 0 :flower.getCaiNum()) ); 
			else if (doCount == 1)
				flower.setFlowersNum(1 + (flower.getFlowersNum() == null ? 0 :flower.getFlowersNum())) ;
			topicService.saveFlower(flower);
		}
		//查询顶、踩的数量
		Map<String, Object> map = topicService.getDingOrCaiNum(topicsId);
		reStr = "{dingNum:'" + map.get("flowersNum") + "',caiNum:'" + map.get("caiNum") +"'}";
		
		if(!ls.isEmpty()&&ls.size()>0){
			response.getWriter().println(reStr);
		}else{
			response.getWriter().println(reStr);
		}
		return null;
	}
	/**
	 * 替换表情
	 * @param commentText
	 * @return
	 */
	private String replaceBianqing(String commentText){
		
		if(StringUtils.isEmpty(commentText)){
			return "";
		}
		 commentText = commentText.replaceAll(":bishi:", "<img src=\"../../themes/images/biaoqing/1.gif\" />")
			.replaceAll(":chongbai:", "<img src=\"../../themes/images/biaoqing/2.gif\" />")
			.replaceAll(":bucuo:", "<img src=\"../../themes/images/biaoqing/3.gif\" />")
			.replaceAll(":bixue:", "<img src=\"../../themes/images/biaoqing/4.gif\" />")
			.replaceAll(":naoni:", "<img src=\"../../themes/images/biaoqing/5.gif\" />")
			.replaceAll(":dise:", "<img src=\"../../themes/images/biaoqing/6.gif\" />")
			.replaceAll(":chaoxiao:", "<img src=\"../../themes/images/biaoqing/7.gif\" />")
			.replaceAll(":buzhidao:", "<img src=\"../../themes/images/biaoqing/8.gif\" />")
			.replaceAll(":kun:", "<img src=\"../../themes/images/biaoqing/9.gif\" />")
			.replaceAll(":meideheng:", "<img src=\"../../themes/images/biaoqing/10.gif\" />")
			.replaceAll(":weiqu:", "<img src=\"../../themes/images/biaoqing/11.gif\" />")
			.replaceAll(":daxiao:", "<img src=\"../../themes/images/biaoqing/12.gif\" />")
			.replaceAll(":daizi:", "<img src=\"../../themes/images/biaoqing/13.gif\" />")
			.replaceAll(":youzai:", "<img src=\"../../themes/images/biaoqing/14.gif\" />")
			.replaceAll(":paomeiyan:", "<img src=\"../../themes/images/biaoqing/15.gif\" />")
			;
		 return commentText;
	 }
	/**
	 * 得到客户端ip
	 * @param request
	 * @return
	 */
	public String getIpAddr(HttpServletRequest request) {
		String ip = request.getHeader("x-forwarded-for");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}
		System.out.print(ip);
		return ip;
	}  

}
